﻿#include "SearchDialog.h"
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QScrollArea>
#include "Custom/CircleButton.h"
#include "Debug.h"
#include "Model/DataCenter.h"

using namespace model;

SearchDialog::SearchDialog(QWidget* parent)
    : QDialog(parent)
{
    init_ui();
    connect_signal();
}

/// @brief 初始化UI
void SearchDialog::init_ui()
{
    /* 初始化基本属性 */
    this->setWindowTitle("全网搜索");
    this->setFixedSize(680, 720);
    this->setWindowIcon(QIcon(":/image/logo.png"));
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setStyleSheet(
        "QWidget{"
        "background-color: #ffffff;"
        "border: none;"
        "}");
    g_layout = new QGridLayout();
    g_layout->setContentsMargins(10, 10, 10, 10);
    g_layout->setSpacing(10);
    this->setLayout(g_layout);
    /* 搜索框 */
    line_edit = new QLineEdit();
    line_edit->setFixedHeight(30);
    line_edit->setPlaceholderText("输入搜索关键字");
    line_edit->setStyleSheet(get_line_edit_style());
    /* 搜索按钮 */
    search_btn = new QPushButton();
    search_btn->setText("搜索");
    search_btn->setFixedSize(50, 30);
    QString blue_btn = get_blue_button_style();
    blue_btn.replace("QPushButton {", "QPushButton { border-radius: 5px; ");  // 移除重复的QPushButton规则，直接在原有样式基础上添加圆角
    search_btn->setStyleSheet(blue_btn);
    /* 初始化滚动区域 */
    QScrollArea* s_area = new QScrollArea();
    s_area->setStyleSheet(SCROLL_STYLE);
    s_area->setWidgetResizable(true);
    s_area->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);  // Expanding便于把搜索框顶上去
    QWidget* container = new QWidget();
    container->setStyleSheet(
        "QWidget {"
        "background-color: #FFFFFF;"
        "border:none;"
        "}");
    s_area->setWidget(container);
    v_layout_scroll = new QVBoxLayout();
    v_layout_scroll->setContentsMargins(0, 0, 0, 0);
    v_layout_scroll->setSpacing(0);
    v_layout_scroll->setAlignment(Qt::AlignTop);
    container->setLayout(v_layout_scroll);
    /* 布局管理器添加元素 */
    g_layout->addWidget(line_edit, 0, 0, 1, 7, Qt::AlignTop);
    g_layout->addWidget(search_btn, 0, 7, 1, 1, Qt::AlignTop);
    g_layout->addWidget(s_area, 1, 0, 1, 8);
    /* 添加测试数据 */
#ifdef TEST_UI
    for (int i = 0; i < 5; ++i) {
        // model::UserInfo* info = new model::UserInfo();
        // info->avatar          = QIcon(":/image/vanilla.png");
        // info->nick_name       = "香草" + QString::number(i + 1);
        // info->description     = "这是一段可爱的个性签名...";
        // add_item(*info);
        /* 这里传指针, 传栈上的对象都可以, 因为在后续的代码里并没有使用引用访问该已经释放的对象.
           而是直接使用 setText(), setIcon() 直接使用该对象里的内容, 这些函数已经实现了深拷贝.
           出作用域后不会再继续使用 info*/
        model::UserInfo info;
        info.avatar      = QIcon(":/image/vanilla.png");
        info.nick_name   = "香草" + QString::number(i + 1);
        info.description = "这是一段可爱的个性签名...";
        add_item(info);
    }
#endif
}

/// @brief 连接信号槽
void SearchDialog::connect_signal()
{
    connect(search_btn, &QPushButton::clicked, this, &SearchDialog::handle_search_btn_clicked);
}

/// @brief 处理搜索按钮点击
void SearchDialog::handle_search_btn_clicked()
{
    DataCenter*    data_center = DataCenter::get_instance();
    const QString& key         = line_edit->text();
    connect(data_center, &DataCenter::search_user_done, this, [=] {
        QList<UserInfo>* user_list = data_center->get_search_user_result();
        if (user_list == nullptr) {
            LOG() << "无搜索结果";
            return;
        }
        for (const auto& user_info : *user_list) {
            add_item(user_info);
        }
    });
    data_center->search_user_async(key);
}

/// @brief 设置输入框的内容
void SearchDialog::set_text(const QString& text)
{
    line_edit->setText(text);
}

/// @brief 添加元素
void SearchDialog::add_item(const model::UserInfo& user_info)
{
    SearchDialogItem* item = new SearchDialogItem(user_info);
    v_layout_scroll->addWidget(item);
}

/// @brief 全部删除
void SearchDialog::clear()
{
    for (int i = v_layout_scroll->count() - 1; i >= 0; --i) {
        QWidget* w = v_layout_scroll->itemAt(i)->widget();
        if (w == nullptr) {
            LOG() << "None Widget!";
        }
        v_layout_scroll->removeWidget(w);
        delete w;
    }
}

/////////////////////////////////////////////
/// 该窗口使用的元素
/////////////////////////////////////////////
SearchDialogItem::SearchDialogItem(const model::UserInfo& user_info)
{
    const static int CONST_ICON_SIZE = 50;
    /* 初始化基本属性 */
    QGridLayout* g_layout_item = new QGridLayout();
    this->setLayout(g_layout_item);
    this->setFixedHeight(CONST_ICON_SIZE + 20);
    g_layout_item->setContentsMargins(10, 0, 20, 0);
    g_layout_item->setHorizontalSpacing(0);
    g_layout_item->setVerticalSpacing(0);
    g_layout_item->setAlignment(Qt::AlignTop);
    g_layout_item->setRowStretch(0, 0);  // 第0行不拉伸
    g_layout_item->setRowStretch(1, 0);  // 第1行不拉伸
    g_layout_item->setRowStretch(2, 1);  // 添加空行占据剩余空间（可选）
    this->setStyleSheet(
        "QLabel {"
        "font-size: 14px;"
        "}");
    /* 按钮 */
    const QSize   icon_size = QSize(CONST_ICON_SIZE, CONST_ICON_SIZE);
    CircleButton* avatar    = new CircleButton();
    avatar->setIcon(user_info.avatar);
    avatar->setFixedSize(icon_size);
    avatar->setIconSize(icon_size);
    /* 昵称和个性签名 */
    QLabel* label1 = new QLabel();
    QLabel* label2 = new QLabel();
    label1->setFixedHeight(CONST_ICON_SIZE / 2);
    label1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    label1->setText(user_info.nick_name);
    label2->setFixedHeight(CONST_ICON_SIZE / 2);
    label2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    label2->setText(user_info.description);
    /* 按钮 */
    btn = new QPushButton();
    btn->setText("加好友");
    btn->setFixedSize(QSize(60, 30));
    btn->setStyleSheet(
        "QPushButton{"
        "font-size: 12px;"
        "border-radius: 5px;"
        "background-color: #F2F2F2;"
        "border: 1px solid #757575;"
        "}"
        "QPushButton:hover {"
        "background-color: #E9E9E9;"
        "}"
        "QPushButton:pressed {"
        "background-color: #D5D5D5;"
        "}");
    /* 向布局中添加元素 */
    g_layout_item->addWidget(avatar, 0, 0, 2, 2, Qt::AlignTop);
    g_layout_item->addWidget(label1, 0, 1, 1, 6, Qt::AlignBottom | Qt::AlignLeft);
    g_layout_item->addWidget(label2, 1, 1, 1, 6, Qt::AlignTop | Qt::AlignLeft);
    // g_layout_item->addWidget(btn, 0, 7, 1, 1, Qt::AlignBottom);
    g_layout_item->addWidget(btn, 0, 7, 2, 1, Qt::AlignVCenter);  // 横跨两行, 垂直居中
    /* 点击btn后发送添加好友请求 */
    connect(btn, &QPushButton::clicked, [=] {
        DataCenter* data_center = DataCenter::get_instance();
        data_center->add_friend_async(user_info.user_id);
        btn->setEnabled(false);
    });
}
